package com.pearl.security.multiloginreject.demo.session.redis;

import cn.hutool.core.util.ObjectUtil;
import com.pearl.security.multiloginreject.demo.util.LoginUtils;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.session.Session;
import org.springframework.session.SingleIndexResolver;

/**
 * @author TD
 * @version 1.0
 * @date 2024/5/15
 */
public class MyPrincipalNameIndexResolver<S extends Session> extends SingleIndexResolver<S> {
    private static final String SPRING_SECURITY_CONTEXT = "SPRING_SECURITY_CONTEXT";
/*    private static final Expression expression = (new SpelExpressionParser()).parseExpression("authentication?.name");*/

    public MyPrincipalNameIndexResolver() {
        super(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME);
    }

    public String resolveIndexValueFor(S session) {
        String principalName = (String)session.getAttribute(this.getIndexName());
        if (principalName != null) {
            return principalName;
        } else {
            Object authentication = session.getAttribute("SPRING_SECURITY_CONTEXT");
            if (ObjectUtil.isNotNull(authentication)){
                SecurityContextImpl context = (SecurityContextImpl) authentication;
                String key = LoginUtils.getKey(context.getAuthentication());
                return key;
            }
            return  null;
        }
    }
}
